package com.company.salarysystem;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

// TXT文件工具类：将内存中的员工信息持久化到TXT
public class TXTFileHandler {
    // 导出员工信息到TXT文件
    public static void saveToTXT(List<Employee> employees, String filePath) {
        // try-with-resources 自动关闭文件流，避免资源泄漏
        try (FileWriter writer = new FileWriter(filePath)) {
            // 写入文件标题和表头
            writer.write("===================== 员工薪资系统存储数据 =====================\n");
            writer.write("存储时间：" + new java.util.Date() + "\n\n");
            writer.write(String.format("%-10s %-8s %-12s %-40s %-10s %-30s\n",
                    "工号", "姓名", "员工类型", "薪资构成", "总薪资", "状态"));
            writer.write("---------------------------------------------------------\n");

            // 遍历内存中的员工，写入TXT
            for (Employee emp : employees) {
                String empType = (emp instanceof RegularEmployee) ? "普通员工" : "管理人员";
                String salaryDetails;
                String totalSalary;
                String status;

                try {
                    salaryDetails = emp.getSalaryDetails();
                    totalSalary = emp.calculateSalary() + "元";
                    status = "正常";
                } catch (IllegalArgumentException e) {
                    salaryDetails = "无（计算异常）";
                    totalSalary = "0元";
                    status = "异常：" + e.getMessage();
                }

                // 格式化数据行，保证对齐
                String line = String.format("%-10s %-8s %-12s %-40s %-10s %-30s\n",
                        emp.empId, emp.name, empType, salaryDetails, totalSalary, status);
                writer.write(line);
            }

            writer.write("=========================================================\n");
            System.out.println("\n数据已成功存储到TXT文件！路径：" + filePath);

        } catch (IOException e) {
            System.out.println("存储TXT文件失败：" + e.getMessage());
        }
    }
}